package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.WXAppRepository;
import cn.hd01.repository.entity.WXApp;
import cn.hd01.service.WXAppService;

import com.github.sd4324530.fastweixin.api.config.ApiConfig;

@Service
public class WXAppServiceImpl extends BaseServiceImpl<WXApp, Integer> implements WXAppService {

	private WXAppRepository repository;

	@Autowired
	public WXAppServiceImpl(WXAppRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public Page<WXApp> findAll(final WXApp wxapp, Pageable pageable) {
		if (wxapp == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<WXApp>() {
			@Override
			public Predicate toPredicate(Root<WXApp> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();

				if (StringUtils.hasText(wxapp.getName())) {
					predicates.add(cb.like(r.get("name").as(String.class), "%" + wxapp.getName() + "%"));
				}

				if (wxapp.getType() != null) {
					predicates.add(cb.equal(r.get("type").as(Integer.class), wxapp.getType()));
				}

				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
	}

	@Override
	public WXApp findByWeixinId(String weixinId) {
		return repository.findByWeixinId(weixinId);
	}

	@Override
	@Cacheable(value = "wxapp", key = "#p0", unless = "#result == null")
	public WXApp findByDomain(String domain) {
		return repository.findByDomain(domain);
	}

	@Override
	public WXApp findByMchId(String mchId) {
		return repository.findByMchId(mchId);
	}

	@Override
	@Cacheable(value = "apiconfig", key = "#p0.domain")
	public ApiConfig getApiConfig(WXApp app) {
		return new ApiConfig(app.getAppId(), app.getAppSecret(), true);
	}
}
